<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||	
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws. 
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.). 
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations). 
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Listing/classes/PhpFox_ServiceListing.class.php, $Author:  $ */

/** Service for working with listing functionality
 * 
 * @package module.listing
 * @version $Id: PhpFox_ServiceListing.class.php 416 2008-03-28 07:20:51Z phpfoxsv $
 *   PHPFox Team ()
 */
class PhpFox_Mod_Listing_ServiceListing extends BaseService
{
    function getCategories()
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        /* @var $oGroupItem PhpFox_Mod_Groups_ItemCategory */

        $sSql = 'SELECT ls.id, ls.name, COUNT(lsm.id) AS cnt 
				 FROM '.App::getT('listing').' ls
				 LEFT JOIN '.App::getT('listing_main').' lsm ON(ls.id=lsm.list_id)
			     GROUP BY ls.id
				 ORDER BY ls.id ASC';
        $aResult = $oGroupItem->oDb->getRows($sSql);
        
        return $aResult; 
    }
    
    function deleteCategory($iCategoryId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        //delete listing category
        $oGroupItem->oDb->query('DELETE FROM '.App::getT('listing_main').' WHERE list_id = '.$iCategoryId);
        //delete category
        $oGroupItem->oDb->query('DELETE FROM `'.App::getT('listing').'` WHERE `id` = "'.$iCategoryId.'"');
        return true;
    }
    
    function _checkCategoryName($sName, $iCategoryId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $sApend = ($iCategoryId) ? ' AND id != '.$iCategoryId : '';
        
        $sSql = 'SELECT COUNT(id) FROM '.$oGroupItem->sTable.' WHERE `name` = "'.$sName.'"'.$sApend;
        
        return ($oGroupItem->oDb->getField($sSql)) ? false :true;
    }
    
    function editCategory($sName, $iCategoryId = 0)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        if(!$this->_checkCategoryName($sName, $iCategoryId))
            return false;
        if($iCategoryId)
            $sSql = 'UPDATE `'.App::getT('listing').'` SET `name` = "'.$oGroupItem->oDb->escape($sName).'" WHERE `id` = "'.$iCategoryId.'"';
        else
            $sSql = 'INSERT INTO `'.App::getT('listing').'` (`name`) VALUES ("'.$oGroupItem->oDb->escape($sName).'")';

        $bResult = $oGroupItem->oDb->query($sSql);
        $this->addErrors($oGroupItem->oDb->getErrors());
        return $bResult;
    }
    
    function getCategoryHash()
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $aRows = $oGroupItem->oDb->getHash('SELECT `id`, `name` FROM '.$oGroupItem->sTable.' ORDER BY `name` ASC');
        foreach ($aRows as $iKey => $sValue)
        {
        	$aRows[$iKey] = App::formatTranslate($sValue);
        }
        return $aRows;
    }
    
    function listCategories()
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        
        $sSql = 'SELECT cat.name, cat.id
                    FROM '.$oGroupItem->sTable.' AS cat
                    ORDER BY cat.name';
        $aCat =  $oGroupItem->oDb->getRows($sSql);
        
        foreach ($aCat as $i=>$aCatSum)
        {
            $aCat[$i]['name'] = App::formatTranslate($aCatSum['name']);
        	$sSql = 'SELECT `title`, `user`, `time`, `id`, location
                        FROM '.App::getT('listing_main').' 
                        WHERE list_id = '.$aCatSum['id'].'
                        ORDER BY `time` DESC
                        LIMIT 0,5';
            $aCat[$i]['listing'] = $oGroupItem->oDb->getRows($sSql);
            foreach($aCat[$i]['listing'] as $j=>$aList)
            {
	            $aCat[$i]['listing'][$j]['bloc'] = true;
	            if(!is_readable(App::getParam('flag.pic.path').$aList['location'].'.gif'))
	                $aCat[$i]['listing'][$j]['bloc'] = false;
	            else 
	                $aCat[$i]['listing'][$j]['srcf'] = App::getParam('flag.pic.url').$aList['location'].'.gif';
            }
        }
        
        return $aCat;
    }
    
    function getListingById($iId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        $oGroupItem->load($iId);
        
        return $oGroupItem->aData;
    }
    
    function checkListingName($sListName, $iCatId, $iListingId = 0)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        
        $sCond = ($iListingId) ? ' AND id != '.$iListingId : '';
        
        $sSql = 'SELECT COUNT(id) FROM '.$oGroupItem->sTable.' WHERE list_id = '.$iCatId.' AND `title` = "'.mysql_escape_string(htmlspecialchars($sListName)).'"'.$sCond;
        
        return $oGroupItem->oDb->getField($sSql) ?  true : false;
    }
    
    function addListing($aData, $sUser)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
                
        $oGroupItem->aData['list_id']     = $aData['category'];
        $oGroupItem->aData['user']        = $sUser;
        $oGroupItem->aData['title']       = $aData['title'];
        $oGroupItem->aData['text']        = $aData['text'];
        $oGroupItem->aData['location']    = $aData['location'];
        $oGroupItem->aData['city']        = $aData['city'];
        $oGroupItem->aData['time']        = time();
        $oGroupItem->aData['views']       = 0;
        $oGroupItem->aData['edit']        = 0;
        $oGroupItem->aData['state']       = !empty($aData['state']) ? $aData['state'] : '';        
        
        $oGroupItem->insert();   
        
        return $oGroupItem->oDb->getLastID();
    }
    
    function updateListing($aData, $sUser, $iListingId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        
        $oGroupItem->aData['id']          = $iListingId;
        $oGroupItem->aData['list_id']     = $aData['category'];
        $oGroupItem->aData['user']        = $sUser;
        $oGroupItem->aData['title']       = $aData['title'];
        $oGroupItem->aData['text']        = $aData['text'];
        $oGroupItem->aData['location']    = $aData['location'];
        $oGroupItem->aData['city']        = $aData['city'];
        $oGroupItem->aData['state']       = !empty($aData['state']) ? $aData['state'] : '';   
             
        $oGroupItem->update();
        
        $oGroupItem->oDb->query('UPDATE '.$oGroupItem->sTable.' SET edit = edit+1 WHERE id ='.$iListingId);
        return true;
    }
    
    function updateView($iListingId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        
        $oGroupItem->oDb->query('UPDATE '.$oGroupItem->sTable.' SET views = views+1 WHERE id ='.$iListingId);
        return true;
    }
    
    function &getListingByCategory($aCond = array(), $iPage=0, $iPageSize=0, $sOrder = '')
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        
        $aRes = $oGroupItem->getList($aCond, $iPage, $iPageSize, $sOrder);
        return $aRes;
    }
    
    function deleteItem($iId)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        $oGroupItem->delete($iId);
        return true;
    }
    
    function _callbackDeleteUser($mParam)
    {
        $oGroupItem = $this->_oModule->getItem('Groups');
        $oGroupItem->_initTable('listing_main');
        $aAccountHash = $mParam['aIds'];
        $oAccServ = &App::getModuleService('Account', 'Account'); 
        
        foreach ($aAccountHash as $iUserId)
        {
            $oAcc = $oAccServ->getById($iUserId);
            $sUser = $oAcc->aData['user'];
            $aListHash = $oGroupItem->oDb->getHash('SELECT `id`, `user` FROM '.$oGroupItem->sTable.' WHERE `user` = "'.$sUser.'"' );
            foreach($aListHash as $iId=>$sUser)
                $this->deleteItem($iId);
        }
        return true;
    }
}

?>